import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_hf/home/recommend_page.dart';
import 'package:provider/provider.dart';
import 'package:xr_base/colors.dart';
import 'package:xr_base/dimens.dart';
import 'package:xr_base/image_constants.dart';
import 'package:xr_base/styles.dart';
import 'package:xr_base/view_util.dart';

import '../provider/home_provider.dart';
import '../widgets/banner_widget.dart';
import '../widgets/custom_under_line.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  late TabController _tcontroller;

  List<CommonType> _categoryList = [
    CommonType(id: '0', name: '约线下', isSelected: false),
    CommonType(id: '1', name: '推荐', isSelected: true),
    CommonType(id: '2', name: '在线', isSelected: false),
    CommonType(id: '3', name: '关注', isSelected: false),
  ];

  @override
  void initState() {
    super.initState();
    _initController();
    _loadData();
  }

  _initController() {
    _tcontroller = TabController(initialIndex: 1, length: _categoryList.length, vsync: this);
    _tcontroller.addListener(() async {
      void _forceUpdate() {
        _categoryList.forEach((element) {
          element.isSelected = false;
        });
        final _selectedLikeTypeData = _categoryList[_tcontroller.index];
        _selectedLikeTypeData.isSelected = true;
        setState(() {
          _categoryList[_tcontroller.index] = _selectedLikeTypeData;
        });
      }

      _forceUpdate();
    });
  }

  _loadData() {
    Future.delayed(Duration(milliseconds: 300), () {
      scheduleMicrotask(() {
        Provider.of<HomeProvider>(context, listen: false).loadBanner();
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Colors.transparent,
      body: WillPopScope(
        onWillPop: () async {
          return false;
        },
        child: SafeArea(
          top: false,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              _headWidget(),
              Expanded(
                child: DefaultTabController(
                    length: 3,
                    child: TabBarView(
                      controller: _tcontroller,
                      children: _categoryList.map((tab) {
                        if (tab.id == '0') {
                          return const RecommendPage();
                        }
                        return const RecommendPage();
                      }).toList(),
                    )),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _headWidget() {
    return Stack(
      alignment: Alignment.topCenter,
      children: [
        localImage(ImageConstants.img_home_bg,
            width: screenWidth(context), height: Dimens.dn_198 + Dimens.dn_86, fit: BoxFit.cover),
        Positioned(
          top: Dimens.dn_59,
          child: Container(
            height: Dimens.dn_28,
            child: TabBar(
              isScrollable: true,
              controller: _tcontroller,

              /// 内间距
              padding: EdgeInsets.zero,

              /// title 间距
              labelPadding: EdgeInsets.only(left: 5, right: 5),
              indicatorSize: TabBarIndicatorSize.label,
              indicator: HomeCustomTabIndicator(
                indicatorWidth: 10,
                borderSide: BorderSide(width: 2, color: Colours.blue_236AF6),
              ),
              indicatorWeight: 2,
              tabs: _categoryList.map<Widget>((tab) {
                return Container(
                  alignment: Alignment.center,
                  width: Dimens.dn_80,
                  child: Text(
                    tab.name ?? '',
                    style: tab.isSelected ? TextStyles.ts_20_w500_000000 : TextStyles.ts_16_400_000000,
                  ),
                );
              }).toList(),
            ),
          ),
        ),
        Positioned(
          top: Dimens.dn_107,
          left: Dimens.dn_15,
          right: Dimens.dn_15,
          child: const BannerWidget(),
        )
      ],
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    super.dispose();
    _tcontroller.dispose();
  }
}

class CommonType {
  String? name;
  String? id;
  int? num;
  String? normalImagePath;
  String? selectedImagePath;
  bool isSelected;

  CommonType({this.name, this.id, this.num, this.normalImagePath, this.selectedImagePath, this.isSelected = false});
}
